package com.zhenwgang.listen_books.servlet.album;

import com.zhenwgang.listen_books.service.AlbumService;
import com.zhenwgang.listen_books.view_object.AlbumVO;
import com.zhenwgang.listen_books.view_object.UserVO;
import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Violet
 * @date 2022/07/14 19:34
 **/
@WebServlet("/studio/album/list.json")
public class ListJsonServlet extends HttpServlet {
    private ObjectMapper objectMapper = new ObjectMapper();
    private List<AlbumVO> list = new ArrayList<>();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession(false);
        if (session == null){
            throw new RuntimeException("用户未登录");
        }
        UserVO currentUser = (UserVO) session.getAttribute("currentUser");
        if (currentUser == null){
            throw new RuntimeException("用户未登录");
        }

        List<AlbumVO> list = new AlbumService().listOfAlbum(currentUser);
        String json = objectMapper.writeValueAsString(list);

        resp.setCharacterEncoding("utf-8");
        resp.setContentType("application/json");
        PrintWriter writer = resp.getWriter();
        writer.println(json);
    }
}